<script setup lang="ts">
import useUtil from '@renderer/composables/useUtil'
import usePeople from '@renderer/composables/usePeople'
import formButton from '@renderer/components/formButton.vue'
import { ref, reactive } from 'vue'
import { Action, ElMessageBox, ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import NavBar from '@renderer/components/navBar.vue'
import uploadAvatarImage from '@renderer/components/uploadAvatarImage.vue'
const initParams = () => ({
  status: '-1',
  type: '',
  super: 0,
  page: 1,
  limit: 10,
})
const initsubmitForm = () => ({
  name: '',
  avatar: 'https://cw3.obs.cn-north-4.myhuaweicloud.com/default/avatar.png',
  phone: '',
  password: '',
  password_confirm: '',
  department: '',
  type: '',
  id_card: '',
  address: '',
  exigency_name: '',
  exigency_phone: '',
  wechat: '',
  alipay: '',
  bank_name: '',
  bank_no: '',
  bank_person: '',
  bank_sub: '',
  status: 1,
  in_time: '',
  remark: '',
  account: '',
})
const queryParams = reactive(initParams())
const submitForm = ref(initsubmitForm())
const ids = ref([])
const showTime = ref('')
const peopleDialog = ref(false)
const currentType = ref<initType>('init')
const dialogType = ref('add')
const statusOptions = [
  {
    value: '-1',
    label: '全部',
  },
  {
    value: '1',
    label: '在职',
  },
  {
    value: '2',
    label: '离职',
  },
]
const peopleOptions = ref<
  {
    value: string
    label: string
  }[]
>([])
const handleQuery = async () => {
  currentType.value = 'search'
  await initData(currentType.value, 1)
}
const handleReset = async () => {
  Object.assign(queryParams, initParams())
  currentType.value = 'init'
  await initData('init', 1)
}
const handleClose = async () => {
  Object.assign(submitForm.value, initsubmitForm())
  showTime.value = ''
  peopleDialog.value = false
  await initData('init', 1)
}
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id)
}
const handleNextPage = async (val: number) => {
  await initData(currentType.value, val)
}
const handleDelPeople = (id: number) => {
  ElMessageBox.alert('删除该员工账号将会清空该账号的所有信息并无法恢复，是否确定要删除该员工账号？', '温馨提示', {
    showCancelButton: true,
    callback: async (action: Action) => {
      if (action == 'confirm') {
        await delPerson({ id })
        await handleReset()
      }
    },
  })
}
const handleAddPeople = () => {
  dialogType.value = 'add'
  peopleDialog.value = true
}
const handleEditPeople = async (id: number) => {
  const userInfo = await getPersonDetail({ id })
  submitForm.value = userInfo
  showTime.value = userInfo.in_time ? dayjs.unix(userInfo.in_time).format('YYYY-MM-DD') : ''
  dialogType.value = 'edit'
  peopleDialog.value = true
}
const handleEditRule = (id: number) => {
  window.api.closeWindow('ruleList', 'destroy')
  window.api.openWindow('ruleList', { title: '权限列表', userId: id, isDisabled: false, userType: 'employee' })
}
const handleTimeChange = (val) => {
  submitForm.value.in_time = dayjs(val).unix() + ''
}
const handleSubmit = async () => {
  if (!submitForm.value.name) {
    ElMessage.error('姓名不能为空')
    return
  }
  if (!submitForm.value.phone) {
    ElMessage.error('电话不能为空')
    return
  }
  if (!submitForm.value.password && dialogType.value == 'add') {
    ElMessage.error('密码不能为空')
    return
  }
  if (!submitForm.value.password_confirm && dialogType.value == 'add') {
    ElMessage.error('确认密码不能为空')
    return
  }
  if (submitForm.value.password != submitForm.value.password_confirm && dialogType.value == 'add') {
    ElMessage.error('两次密码输入不一致')
    return
  }
  if (!submitForm.value.type) {
    ElMessage.error('身份不能为空')
    return
  }
  if (!submitForm.value.account) {
    ElMessage.error('账号不能为空')
    return
  }
  if (dialogType.value == 'add') {
    if (await addPerson(submitForm.value)) {
      await handleClose()
    }
  } else {
    if (await updatePersonInfo(submitForm.value)) {
      await handleClose()
    }
  }
}
const handleAvatar = (url: string) => {
  submitForm.value.avatar = url
}
const initData = async (type: initType, page: number) => {
  const params = {
    type: type == 'init' ? '' : queryParams.type,
    status: type == 'init' ? '-1' : queryParams.status,
    super: 0,
    page,
    limit: queryParams.limit,
  }
  if (type == 'init') {
    peopleOptions.value = []
    const indentityList = await handleGetIdentity()
    indentityList.forEach((item) => {
      peopleOptions.value.push({
        value: item,
        label: item,
      })
    })
  }
  await getPersonList(params)
}
const { handleGetIdentity } = useUtil()
const { getPersonList, peopleList, delPerson, addPerson, getPersonDetail, updatePersonInfo } = usePeople()
initData('init', 1)
</script>

<template>
  <main class="bg-white flex flex-col gap-3 rounded-md" style="height: -webkit-fill-available">
    <el-form :model="queryParams" inline>
      <el-form-item label="员工身份">
        <el-select v-model="queryParams.type" placeholder="请选择" style="width: 150px">
          <el-option v-for="item in peopleOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="员工状态">
        <el-select v-model="queryParams.status" placeholder="请选择" style="width: 150px">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <div class="flex gap-3">
        <formButton @click="handleQuery"> 搜索 </formButton>
        <formButton @click="handleReset"> 重置 </formButton>
        <formButton @click="handleAddPeople"> 添加员工 </formButton>
      </div>
    </el-form>
    <el-table
      :data="peopleList?.data"
      border
      header-align="center"
      :header-cell-style="{ background: '#FFF4E5', fontSize: '14px', color: '#888', fontWeight: '400' }"
      @selection-change="handleSelectionChange">
      <el-table-column type="index" label="序号" align="center" width="55" />
      <el-table-column prop="name" label="员工姓名" align="center" />
      <el-table-column prop="type" label="员工身份" align="center" />
      <el-table-column prop="phone" label="电话" align="center" />
      <el-table-column label="操作" align="center" width="290">
        <template #default="scope">
          <el-button type="warning" plain size="small" @click="handleEditPeople(scope.row.id)">编辑员工</el-button>
          <el-button type="danger" plain size="small" @click="handleDelPeople(scope.row.id)">删除员工</el-button>
          <el-button type="info" plain size="small" @click="handleEditRule(scope.row.id)">查看权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="handleNextPage"
      :current-page="peopleList?.current_page"
      :page-size="queryParams.limit"
      :total="peopleList?.total"
      background
      hide-on-single-page
      class="flex-1 items-end" />
    <el-dialog v-model="peopleDialog" width="500" align-center :show-close="false" style="padding: 0">
      <div class="flex flex-col pb-4 gap-5">
        <NavBar @handleClose="handleClose" :title="dialogType == 'edit' ? '编辑员工' : '添加员工'" />
        <div style="height: 550px" class="overflow-y-auto">
          <el-form class="px-6 flex flex-col gap-2" label-width="120">
            <el-form-item label="头像:">
              <uploadAvatarImage :modelValue="submitForm.avatar" @finish="handleAvatar" />
            </el-form-item>
            <el-form-item label="姓名:" required>
              <el-input v-model="submitForm.name" placeholder="请输入姓名" clearable />
            </el-form-item>
            <el-form-item label="手机号:" required>
              <el-input v-model="submitForm.phone" placeholder="请输入手机号" clearable type="number" @mousewheel.native.prevent />
            </el-form-item>
            <el-form-item label="账号:" required>
              <el-input v-model="submitForm.account" placeholder="请输入3-12位字母、数字或组合" clearable />
            </el-form-item>
            <el-form-item label="密码:" required v-if="dialogType == 'add'">
              <el-input
                v-model="submitForm.password"
                placeholder="请输入8-12位字母、数字或组合"
                clearable
                type="password"
                show-password />
            </el-form-item>
            <el-form-item label="再次输入密码:" required v-if="dialogType == 'add'">
              <el-input
                v-model="submitForm.password_confirm"
                placeholder="请再次输入密码"
                clearable
                type="password"
                show-password />
            </el-form-item>
            <el-form-item label="所在部门:">
              <el-input v-model="submitForm.department" placeholder="请输入所在部门" clearable />
            </el-form-item>
            <el-form-item label="身份:" required>
              <el-select v-model="submitForm.type" placeholder="请选择身份" class="flex-1">
                <el-option v-for="item in peopleOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="身份证号:">
              <el-input v-model="submitForm.id_card" placeholder="请输入身份证号" clearable type="number" @mousewheel.native.prevent />
            </el-form-item>
            <el-form-item label="家庭住址:">
              <el-input v-model="submitForm.address" placeholder="请输入家庭住址" clearable />
            </el-form-item>
            <el-form-item label="紧急联系人:">
              <el-input v-model="submitForm.exigency_name" placeholder="请输入紧急联系人" clearable />
            </el-form-item>
            <el-form-item label="联系人手机号:">
              <el-input v-model="submitForm.exigency_phone" placeholder="请输入联系人手机号" clearable type="number" @mousewheel.native.prevent />
            </el-form-item>
            <el-form-item label="微信号:">
              <el-input v-model="submitForm.wechat" placeholder="请输入微信号" clearable />
            </el-form-item>
            <el-form-item label="支付宝:">
              <el-input v-model="submitForm.alipay" placeholder="请输入支付宝" clearable />
            </el-form-item>
            <el-form-item label="持卡银行:">
              <el-input v-model="submitForm.bank_name" placeholder="请输入持卡银行" clearable />
            </el-form-item>
            <el-form-item label="银行卡号:">
              <el-input v-model="submitForm.bank_no" placeholder="请输入银行卡号" clearable type="number" @mousewheel.native.prevent />
            </el-form-item>
            <el-form-item label="持卡人:">
              <el-input v-model="submitForm.bank_person" placeholder="请输入持卡人" clearable />
            </el-form-item>
            <el-form-item label="支行名称:">
              <el-input v-model="submitForm.bank_sub" placeholder="请输入支行名称" clearable />
            </el-form-item>
            <el-form-item label="入职时间:">
              <el-date-picker
                v-model="showTime"
                type="date"
                placeholder="请选择入职时间"
                class="flex-1"
                @change="handleTimeChange" />
            </el-form-item>
            <el-form-item label="备注:">
              <el-input v-model="submitForm.remark" placeholder="请输入备注" clearable />
            </el-form-item>
            <el-form-item label="员工状态:">
              <el-radio-group v-model="submitForm.status" placement="row">
                <el-radio label="在职" :value="1" />
                <el-radio label="离职" :value="2" />
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <div class="flex justify-center">
          <div class="save-button" @click="handleSubmit">提交</div>
        </div>
      </div>
    </el-dialog>
  </main>
</template>

<style lang="scss" scoped>
.el-form {
  display: flex;
}
.el-form-item {
  margin-bottom: 0px;
  margin-right: 20px !important;
}

::v-deep .el-dialog__header {
  padding-bottom: 0 !important;
}

.save-button {
  @apply text-white px-16 py-3 rounded-md cursor-pointer;
  background: linear-gradient(142deg, #ff9600 0%, #ffb242 100%);
}
::v-deep .el-radio__input.is-checked + .el-radio__label {
  color: #ff9600 !important;
}
::v-deep .el-radio__input.is-checked .el-radio__inner {
  background: #ff9600 !important;
  border-color: #ff9600 !important;
}
</style>
